var tipfy = tipfy || {};

tipfy.MediaManager = function(callback) {
    this.callback = callback;
    this.dialog = new goog.ui.Dialog();
    this.tabBar = new goog.ui.TabBar();
    this.dialog.setTitle('Select a file');
    this.dialog.setButtonSet(null);

    // Content to be loaded using AJAX.
    this.tabContents = null;
    this.galleryContent = null;
};

tipfy.MediaManager.prototype.setSelectedTabContent = function(tabId) {
    var display,
        _this = this,
        activeId = tabId + '-content';

    goog.array.map(this.tabContents,
        function(content) {
            display = content.id == activeId ? 'block' : 'none';
            goog.style.setStyle(content, 'display', display);

            if(tabId == 'tipfy-media-manager-gallery' && !this.galleryContent) {
                var request = new goog.net.XhrIo();
                goog.events.listen(request, 'complete',
                    function() {
                        var el = goog.dom.getElement(content);
                        if (request.isSuccess()) {
                            el.setContent(request.getResponseText());
                        } else {
                            // TODO
                            el.setContent('failure');
                        }
                    }
                );
                request.send('/_widgets/media-manager-list', 'GET', null, {
                    'X-REQUESTED-WITH': 'XMLHttpRequest',
                });
            }
        }
    );
};

tipfy.MediaManager.prototype.showDialog = function() {
    this.dialog.setVisible(true);

    if(!this.tabContents) {
        var request = new goog.net.XhrIo(),
            _this = this;
        goog.events.listen(request, 'complete',
            function() {
                if (request.isSuccess()) {
                    _this.dialog.setContent(request.getResponseText());
                    _this.tabBar.decorate(goog.dom.getElement('tipfy-media-manager'));
                    _this.tabContents = goog.dom.query('#tipfy-media-manager-content .goog-tab-content');

                    // Handle SELECT events dispatched by tabs.
                    goog.events.listen(_this.tabBar, goog.ui.Component.EventType.SELECT,
                        function(e) {
                            _this.setSelectedTabContent(e.target.getId());
                        }
                    );
                    _this.setSelectedTabContent('tipfy-media-manager-upload');
                } else {
                    // TODO
                    _this.dialog.setContent('failure');
                }
            }
        );

        request.send('/_widgets/media-manager', 'GET', null, {
            'X-REQUESTED-WITH': 'XMLHttpRequest',
        });
    } else {
        this.tabBar.setSelectedTabIndex(0);
    }
};
